namespace tools {

	let $userInfoBtn: wx.UserInfoButton;

	export function sizeTransfer(options: hjc.TGameSize): hjc.TWxSize {
		let ratio = ui.getStageWidth() / wx.getSystemInfoSync().screenWidth;
		let tws = { width: options.width, height: options.height, left: 0, top: 0 };
		if (numeric(options.x)) tws.left += options.x;
		if (numeric(options.y)) tws.top += options.y;
		if (numeric(options.hc)) tws.left = (game.width - tws.width) / 2 + options.hc;
		if (numeric(options.vc)) tws.top = (game.height - tws.height) / 2 + options.vc;
		for (let prop in tws) { tws[prop] *= game.scale; }
		tws.left += game.paddingLR; tws.top += game.paddingTB;
		for (let prop in tws) { tws[prop] /= ratio; }
		return tws;
	}

	export function showUserInfoBtn(img: string, size: hjc.TGameSize, next?: (res: wx.TAuthResult) => void): void {
		if (!$userInfoBtn) {
			let wxSize = sizeTransfer(size);
			let options: wx.TUserInfoButton = {
				type: 'image', image: `resource/img/${img}`, style: {
					left: wxSize.left, top: wxSize.top,
					width: wxSize.width, height: wxSize.height
				}, withCredentials: true,
			};
			$userInfoBtn = wx.createUserInfoButton(options);
		}
		$userInfoBtn.show();
		if (isFunc(next)) $userInfoBtn.onTap((res: wx.TAuthResult) => next(res));
	}

	export function hideUserInfoBtn(): void {
		if ($userInfoBtn) $userInfoBtn.hide();
	}

	export function createDisplayObject(type: string, width: number, height: number): egret.Bitmap {
		let sharedCanvas = wx.getOpenDataContext().canvas

		const bitmapdata = new egret.BitmapData(sharedCanvas);
		bitmapdata.$deleteSource = false;
		const texture = new egret.Texture();
		texture._setBitmapData(bitmapdata);
		const bitmap = new egret.Bitmap(texture);
		bitmap.width = width;
		bitmap.height = height;

		if (egret.Capabilities.renderMode == "webgl") {
			const renderContext = egret['wxgame'].WebGLRenderContext.getInstance();
			const context = renderContext.context;
			////需要用到最新的微信版本
			////调用其接口WebGLRenderingContext.wxBindCanvasTexture(number texture, Canvas canvas)
			////如果没有该接口，会进行如下处理，保证画面渲染正确，但会占用内存。
			if (!context.wxBindCanvasTexture) {
				egret.startTick((timeStarmp) => {
					egret.WebGLUtils.deleteWebGLTexture(bitmapdata.webGLTexture);
					bitmapdata.webGLTexture = null;
					return false;
				}, this);
			}
		}
		return bitmap;
	}
}

